﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.IO.Ports;
using DigtiMatrix.Entity;
using DigitMatrix.Business;

namespace TunnelPrj.YunTai
{
    class ConnectionManager
    {
        private readonly Dictionary<string,SerialPort> _connections
            = new Dictionary<string, SerialPort>();
        //
        public void Close(CamercaInfo oCamInfo)
        {
            if (_connections.ContainsKey(oCamInfo.ConnURL))
            {
                SerialPort oStream = _connections[oCamInfo.ConnURL];
                oStream.Close();
                _connections.Remove(oCamInfo.ConnURL);
            }
        }
        public SerialPort GetConnection(CamercaInfo oCamInfo)
        {
           
            if (!_connections.ContainsKey(oCamInfo.ConnURL))
            {
                
                     
                    int dataBit =  Config.DataBit;
                    int baudRate = Config.BaudRate;
                    System.IO.Ports.Parity parity = (System.IO.Ports.Parity)Config.Parity;
                    StopBits stopbit = (StopBits)Config.StopBit;
                    try
                    {
                        var com = new System.IO.Ports.SerialPort(oCamInfo.ConnURL, baudRate, parity, dataBit, stopbit);
                        com.WriteTimeout = Config.WriteTimeout;
                        com.ReadTimeout = Config.ReadTimeout;
                        com.Open();
                        _connections.Add(oCamInfo.ConnURL, com);

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                 
            }

            return _connections[oCamInfo.ConnURL];
        }
    }
}
